package cn.toolck.listener;

import cn.toolck.config.DataSource;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Map;

@Component
public class RabbitmqListener {
    @RabbitListener(queues = "queue.toolck.pay.dlx",ackMode = "MANUAL")
    public void checkOrder(Message message, Channel channel) throws Exception {
        final String messageStr = new String(message.getBody(), message.getMessageProperties().getContentEncoding());
        System.out.println(messageStr);
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> messageObject = objectMapper.readValue(messageStr, new TypeReference<Map<String, Object>>() {
        });
        DataSource.orderMap.remove(messageObject.get("orderId"));
        // 手动确认消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
